<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="filter-container">
      <el-row :gutter="0">
        <el-form :inline="true" class="search-form">
          <el-form-item label="">
            <el-input v-model="query.name" class="filter-item" placeholder="名称" style="width: 150px;" clearable/>
          </el-form-item>
          <el-form-item label="">
            <el-cascader
              v-model="query.cate_ids"
              class="filter-item"
              :options="categoryData"
              :props="{checkStrictly: false, value: 'id', label: 'name', multiple: true}"
              placeholder="分类"
              style="height:28px"
              collapse-tags
              clearable
              filterable
              :show-all-levels="false"
              @change="pickCategoryQuery"
            >
              <template slot-scope="{ node, data }">
                <span>{{ data.name }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item>
            <el-form-item label="">
              <el-select v-model="query.time_type" class="" placeholder="时间类型">
                <el-option value="created_at" label="添加时间" />
                <el-option value="updated_at" label="修改时间" />
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-date-picker
                v-model="query.range_date"
                type="daterange"
                class="filter-item"
                range-separator="-"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 240px"
              />
            </el-form-item>
          </el-form-item>
          <el-form-item>
            <el-button class="" type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button class="" type="success" icon="el-icon-refresh-right" plain @click="refresh()">刷新</el-button>
          </el-form-item>

          <el-form-item style="float: right">
            <router-link :to="addLink">
              <el-button class="" type="primary">添加</el-button>
            </router-link>
          </el-form-item>
        </el-form>
      </el-row>

      <el-row :gutter="0">
        <el-col :xs="24" :sm="16">
          <div class="left-panel">
            <el-button class="filter-item" type="danger" icon="el-icon-delete" size="mini" @click="batchDel(selection)">批量删除</el-button>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8">
          <div class="right-panel el-button-group">
            <el-button class="" icon="el-icon-refresh" size="mini" @click="refresh"></el-button>
            <el-dropdown trigger="click" :hide-on-click="false">
            <span class="el-dropdown-link">
              <el-button class="" icon="el-icon-s-operation" size="mini"></el-button>
            </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="fruit in allTableThead" :key="fruit">
                  <el-checkbox v-model="checkboxTableThead" :label="fruit">{{ tableTheadOptions[fruit].label }}</el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table ref="tableRef" v-loading="loading" :data="datas" :max-height="height-20" style="width: 100%" border @sort-change="sorting" row-key="id" @selection-change="select">
      <el-table-column type="selection" min-width="40" align="center" show-overflow-tooltip/>
      <el-table-column prop="id" label="ID" min-width="60" align="center" sortable="custom"/>
      <el-table-column prop="cover_img" label="封面图" min-width="70" align="center">
        <template slot-scope="scope">
          <el-image v-if="scope.row.full_cover_img" :src="scope.row.full_cover_img" :preview-src-list="coverImgList"/>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="120" align="center"/>
      <el-table-column prop="cate_name" label="分类" min-width="100" align="center"/>
      <el-table-column prop="status" label="状态" min-width="75" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status_name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sorting" label="排序" min-width="75" align="center" sortable="custom"/>
      <el-table-column prop="created_at" label="创建时间" min-width="160" align="center" sortable="custom"/>
      <el-table-column v-for="fruit in tableThead" :key="fruit" :label="tableTheadOptions[fruit].label" min-width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row[fruit] }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="160" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="query.page" :limit.sync="query.limit" @pagination="list"/>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import Pagination from '@/components/Pagination'
import { list, del, cateList as categoryList } from '@/api/admin/article'

const tableTheadOption = {
  hits: {
    label: '点击数',
    field: 'hits'
  },
  likes: {
    label: '点赞数',
    field: 'likes'
  },
  is_show: {
    label: '是否显示',
    field: 'is_show'
  },
  is_top: {
    label: '是否置顶',
    field: 'is_top'
  },
  is_recommend: {
    label: '是否推荐',
    field: 'is_recommend'
  }
}

const allTableThead = ['hits', 'likes', 'is_show', 'is_top', 'is_recommend']
const defaultTableThead = ['hits', 'likes', 'is_show']

export default {
  name: 'AdminArticle',
  components: {Pagination},
  directives: {},
  data() {
    return {
      name: '内容',
      height: 680,
      loading: false,
      datas: [],
      total: 0,
      query: {
        page: 1,
        limit: 20,
        cate_ids: '',
        time_type: 'created_at',
        date_value: ''
      },

      coverImgList: [],
      categoryData: [],
      selection: [], // 选中项

      tableKey: 1, // table key
      tableTheadOptions: tableTheadOption,
      allTableThead: allTableThead,
      tableThead: defaultTableThead, // 默认表头
      checkboxTableThead: defaultTableThead, // 默认表头值

      addLink: '/admin/article/add',
      editLink: '/admin/article/edit/'
    }
  },
  watch: {
    checkboxTableThead(valArr) {
      this.tableThead = this.allTableThead.filter(i => valArr.indexOf(i) >= 0)
      this.tableKey = this.tableKey + 1 // 为了保证table 每次都会重渲
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
    this.category()
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'info',
        90: 'danger'
      }
      return statusMap[status]
    }
  },
  methods: {
    // 列表
    list() {
      this.loading = true
      list(this.query).then(res => {
        this.datas = res.data.data
        this.total = res.data.total
        this.datas.forEach(item => {
          this.coverImgList.push(item.full_cover_img)
        })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 修改
    edit(row) {
      this.$router.push(this.editLink + row.id)
    },
    // 删除
    del(row) {
      if (!row.length) {
        this.selectMsg()
      } else {
        var title = '删除' + this.name
        var message = '确定要删除选中的 <span style="color:red">' + row.length + ' </span> 条' + this.name + '数据吗？'
        if (row.length === 1) {
          title = title + 'ID：' + row[0].id
          message = '确定要删除' + this.name + ' <span style="color:red">' + row[0].name + ' </span> 这条数据吗？'
        }
        this.$confirm(message, title, {type: 'warning', dangerouslyUseHTMLString: true}).then(() => {
          this.loading = true
          del({
            data: row
          }).then(res => {
            this.loading = false
            if (res.status == 1) {
              this.list()
              this.reset()
              this.$message.success(res.msg)
            } else {
              this.$message.info(res.msg)
            }
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {
        })
      }
    },
    // 重置
    reset() {
      this.model = this.$options.data().model
    },
    // 查询
    search() {
      this.query.page = 1
      this.list()
    },
    // 刷新
    refresh() {
      this.query = this.$options.data().query
      this.list()
    },
    // 排序
    sorting(sort) {
      this.query.sort_field = sort.prop
      this.query.sort_value = ''
      if (sort.order === 'ascending') {
        this.query.sort_value = 'asc'
        this.list()
      }
      if (sort.order === 'descending') {
        this.query.sort_value = 'desc'
        this.list()
      }
    },

    // 全选操作 -- table 表头
    select(selection) {
      this.selection = selection
    },
    selectMsg(message = '') {
      this.$alert(message || '请选择需要操作的' + this.name, '提示', {
        confirmButtonText: '确定', callback: action => {
        }
      })
    },
    // 批量删除
    batchDel(row) {
      this.del(row)
    },

    // 分类获取
    category() {
      categoryList().then(res => {
        this.categoryData = res.data.data
      }).catch(() => {
      })
    },
    // 分类选择 -- 查询
    pickCategoryQuery(value) {
      if (value) {
        //this.query.cate_ids.push(value[value.length - 1])
      }
    }
  }
}
</script>

<style scoped>
.el-table .el-image {
  width: 40px;
  height: 40px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
